import { Ref, ref } from 'vue'
import clusterIcon from '@/assets/img/icon/pointBg.png'
/**
 * 根据Marker数据创建marker点
 * @param markerRefs 已有marker点数据数组
 * @param newMarkers 记录未添加到markerRefs数组的marker对象数据
 * @param markerData 所有marker点数据数组
 * @param onClick 点击marker回调函数
 */
const { AMap } = window as any
let currentMapObj: any = null
const count = ref<number>(0)
export function createMarker(
  currentMap: any,
  markerData: Array<any>,
  cluster: Ref<any>,
) {
  //遍历生成多个标记点
  if (markerData.length === 0) {
    console.log(markerData.length, 'mmmmmm')

    return
  }
  count.value = markerData.length
  markerData.forEach((v) => {
    v.lnglats = v.lnglat
  })
  currentMapObj = currentMap
  cluster.value = new AMap.MarkerClusterer(currentMap, markerData, {
    gridSize: 60,
    // maxZoom: 1,
    clusterByZoomChange: false,
    // styles: [
    //   {
    //     url: clusterIcon,
    //     size: new AMap.Size(68, 68),
    //     offset: new AMap.Pixel(-30, -30),
    //     textColor: '#fff',
    //     textSize: 14,
    //   },
    // ],
    renderMarker: _renderMarker,
    renderClusterMarker: _renderClusterMarker,
  })
}
const _renderClusterMarker = function (context: any) {
  const div = document.createElement('div')
  div.style.background = `url('${clusterIcon}')no-repeat fixed  center`
  const size = 60
  div.style.textAlign = 'center'
  div.style.lineHeight = size + 'px'
  div.style.color = '#fff'
  div.setAttribute('class', 'cluster')
  div.style.width = size + 'px'
  div.style.height = size + 'px'
  div.style.borderRadius = '50%'
  div.innerHTML = context.count
  context.marker.setOffset(new AMap.Pixel(-size / 2, -size / 2))
  context.marker.setContent(div)
  context.marker.on('click', (e: any) => {
    let currentZoom = currentMapObj.getZoom()
    currentZoom++
    currentMapObj.setZoomAndCenter(currentZoom, e.lnglat)
  })
}
const _renderMarker = function (context: any) {
  context.marker.setLabel({
    content: context.data[0].label,
    offset: new AMap.Pixel(-15, -15),
    direction: 'top',
  })
  const content = `<div class="markerIcon"></div>`
  const offset = new AMap.Pixel(-9, -9)
  // 给marker添加点击事件
  context.marker.on('click', (e: any) => {
    e.target.content = JSON.stringify([context.data[0].content])
    e.target.title = context.data[0].title
    e.target.lnglat = context.data[0].lnglat
    e.target.onClick = context.data[0].onClick
    e.target.onClick({
      markerId: e.target.id,
      lng: e.lnglat.lng || 0,
      lat: e.lnglat.lat || 0,
      content: context.data[0],
    })
  })
  context.marker.setContent(content)
  context.marker.setOffset(offset)
}
